﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.DAL;
using Newtonsoft.Json;
using RN.ERP.Entity;
using RN.ERP.BLL.Utilities;
using RN.ERP.ZbdlryDAL;
using Fly.Log;
using RN.ERP.Entity.ResultModels;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using RN.ERP.DAL.Context;
using RN.ERP.DAL.DAL;
using Fly.FlyCommon;
using RN.ERP.Entity.WF;

namespace RN.ERP.BLL.WF
{
    public class PersonBLL : BasePersonBLL
    {
        #region dbContext
        private WFDATA_Context wfContext
        {
            get
            {
                return (WFDATA_Context)base.baseContext;
            }
        }

        public PersonBLL()
        {
            base.baseContext = new WFDATA_Context();
        }
        #endregion

        protected override IQueryable<DTO.V_CheckXMFZR> GetXMFZRQuery()
        {
            var dbUsers = wfContext.T_Sys_Users;
            var dbEmp = wfContext.Emp_Manager;
            var dbTitleDetails = wfContext.Emp_Qualities;
            return from users in dbUsers
                   join emps in dbEmp on users.UserGuid equals emps.CorpGuid
                   join details in dbTitleDetails on emps.EmpGuid equals details.EmpGuid
                   select new DTO.V_CheckXMFZR()
                   {
                       ID = emps.ID,
                       EmpGuid = emps.EmpGuid,
                       //ITypeFlag = details.TypeFlags,
                       TypeFlag = System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)details.TypeFlags).Trim(),
                       bGrade = users.RoleID,
                       CertificateLevel = details.CertificateLevel,
                       EmpName = emps.Name,
                       CLCode = details.CLCode
                   };
        }

        private string GetLevel(string clCode)
        {
            switch (clCode)
            {
                case "一级":
                case "壹级":
                    return "1";
                case "二级":
                case "贰级":
                    return "2";
                case "三级":
                case "叁级":
                    return "3";
                default:
                    return "-99";
            }
        }
        /// <summary>
        /// 人员押证查询-获取人员信息--2013-5-14修改，人员押证在项目库中验证
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            IList<DTO.V_CheckXMFZR> managers = new List<DTO.V_CheckXMFZR>();
            string[] typeFlag = { "0","1" };////人员类型是项目经理
            ////取施工企业项目经理，如果有。
            var query = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == 15 && typeFlag.Contains(p.TypeFlag ?? "-99"));
            managers = query.ToList();
            if (managers.Count > 0)
            {
                result = "0," + managers[0].ID + ":" +
                    managers[0].ITypeFlag.ToString() + ":" +
                    managers[0].bGrade + ":" +
                     GetLevel(managers[0].CLCode);
            }
            else
            {
                typeFlag = new string[] { "2", "40", "72" };////人员类型是项目总监
                ////取监理企业项目负责人，如果有，取等级最高的。
                managers = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == 42 && typeFlag.Contains(p.TypeFlag ?? "-99")).ToList();
                if (managers.Count > 0)
                {
                    int lvl = 0;
                    DTO.V_CheckXMFZR manager = null;
                    foreach (DTO.V_CheckXMFZR item in managers)
                    {
                        int ilvl = -1;
                        int.TryParse(item.CertificateLevel, out ilvl);
                        if (ilvl == -1 || (ilvl >= lvl && lvl > 0))
                        {
                            continue;
                        }
                        else
                        {
                            lvl = ilvl;
                            manager = item;
                        }
                    }
                    string Level = manager.CertificateLevel;
                    if (lvl == 0)
                    {
                        Level = "-1";
                        // result = "9,此人员（项目总监）尚未设置项目总监证书等级。";
                    }
                    result = "0," + manager.ID + ":" +
                           manager.ITypeFlag.ToString() + ":" +
                           manager.bGrade + ":" +
                           Level;
                }
                else
                {
                    result = "9,此人员可能存在以下问题：1.人员信息不存在或未审核通过 2.此人员没有项目负责人资格。";
                }
            }
            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 押证查询
        /// </summary>
        /// <param name="empId">ID或GUID</param>
        /// <param name="roleId">企业roleid</param>
        /// <returns></returns>
        public override string CheckXMFZR(string empId, string roleId, string areaCode)
        {
            string result = string.Empty;
            Guid empGuid = Guid.Empty;
            int empIntId = 0;
            if (string.IsNullOrEmpty(empId))
            {
                result = "9,参数不能为空.";
                return JsonConvert.SerializeObject(result);
            }
            ////值不为GUID
            if (!Guid.TryParse(empId, out empGuid))
            {
                if (int.TryParse(empId, out empIntId))
                {
                    empGuid = GetXMFZRQuery().Where(p => p.ID == empIntId).Select(p => p.EmpGuid).FirstOrDefault();
                    if (empGuid == Guid.Empty)
                    {
                        result = "9,人员empGuid不能为空.";
                        return JsonConvert.SerializeObject(result);
                    }
                }
                else
                {
                    result = "9,传入的参数格式不正确.";
                    return JsonConvert.SerializeObject(result);
                }
            }
            int bGrade = -1;
            if (!int.TryParse(roleId, out bGrade))
            {
                result = "9,传入的参数RoleId格式不正确.";
                return JsonConvert.SerializeObject(result);
            }
            ////按地区取得押证设置表数据
            var emp_ManagerCert = wfContext.emp_ManagerCertCount.Where(e => e.RoleId == roleId && (!e.IsDel ?? true) && e.AreaCode == areaCode.Substring(0,2)).OrderByDescending(e => e.SortCode);
            var TypeFlag = emp_ManagerCert.Select(m => m.TypeFlag).ToList();////押证人员类型
            IList<DTO.V_CheckXMFZR> managers = new List<DTO.V_CheckXMFZR>();
            ////取得人员信息
            var query = GetXMFZRQuery().Where(p => p.EmpGuid == empGuid && p.bGrade == bGrade && TypeFlag.Contains(p.TypeFlag ?? "-99"));
            managers = query.ToList();
            if (managers == null)
            {
                result = "9,此人员可能存在以下问题：1.人员信息不存在或未审核通过 2.此人员没有项目负责人资格。";
                return JsonConvert.SerializeObject(result);
            }
            List<string> empTypeFlag = new List<string>();
            for (int i = 0; i < managers.Count; i++)
            {
                managers[i].CertificateLevel = GetLevel(managers[i].CLCode);////格式化等级
                if (!empTypeFlag.Contains(managers[i].TypeFlag))
                {
                    empTypeFlag.Add(managers[i].TypeFlag);
                }
            } 
            var CertLevel = managers.Select(m => m.CertificateLevel);////证书等级
            ////取得押证数量
            int CertCount = emp_ManagerCert.Where(e => empTypeFlag.Contains(e.TypeFlag) && (CertLevel.Contains(e.CertLevel) || e.CertLevel == "-99")).OrderByDescending(e => e.SortCode).Select(e => e.CertCount ?? 0).FirstOrDefault();
            if (CertCount > 0)
            {
                result = "0," + managers[0].ID + ":" + CertCount.ToString() + ":" + managers[0].EmpName;
            }
            else
            {
                result = "9,人员既不是监理企业项目总监也不是施工企业项目经理.";
            }
            return JsonConvert.SerializeObject(result);
        }

    }
}
